package com.ruoyi.qywx.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.ErrorConstants;
import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.entity.ContactGreet;
import com.ruoyi.qywx.entity.ContactGreetWelcome;
import com.ruoyi.qywx.entity.QyWelcomeTemplate;
import com.ruoyi.qywx.getway.api.ContactWayApi;
import com.ruoyi.qywx.mapper.ContactGreetMapper;
import com.ruoyi.qywx.model.vo.ContactGreetVo;
import com.ruoyi.qywx.model.vo.ContactVo;
import com.ruoyi.qywx.model.vo.WelcomeVo;
import com.ruoyi.qywx.service.inters.ContactPubGreetService;
import com.ruoyi.qywx.service.inters.ContactService;
import com.ruoyi.qywx.service.inters.WelcomeService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : hcl
 * @Date : 2023/8/28 11:38
 */
@Service
public class ContactPubGreetServiceImpl implements ContactPubGreetService {
    @Resource
    private ContactGreetMapper greetMapper;
    @Autowired
    private WelcomeService welcomeService;
    @Autowired
    private ContactService contactService;

    @Transactional
    @Override
    public AjaxResult addGreet(ContactGreetVo greetVo, Meta meta) {
        Map<String, String> users = greetVo.getUsers().stream()
                .collect(Collectors.toMap(ContactVo::getId, ContactVo::getName));

//        String error = ContactWayApi.allowExternalOfUsers(users, meta);
//        if (StrUtils.isNotEmpty(error)) {
//            return AjaxResult.error(error);
//        }
        QyWelcomeTemplate template = greetVo.getWelcome().turnEntity(null);
        welcomeService.insert(template);

        greetMapper.insert(ContactGreet.builder()
                .title(greetVo.getTitle())
                .users(greetVo.getUsers().stream().map(ContactVo::getId)
                        .collect(Collectors.joining(StrUtils.COMMA)))
                .welcomeId(template.getId())
                .teamId(meta.getTeamId())
                .creator(greetVo.getCreator())
                .build());
        return AjaxResult.success();
    }

    @Transactional
    @Override
    public AjaxResult editGreet(ContactGreetVo greetVo, Meta meta) {
        if (!NumberUtils.isTrue(greetVo.getId())) {
            return AjaxResult.error(ErrorConstants.NO_DATA);
        }
        ContactGreet contactGreet = greetMapper.selectById(greetVo.getId());
        if (Objects.isNull(contactGreet) || !contactGreet.getTeamId().equals(meta.getTeamId())) {
            return AjaxResult.error(ErrorConstants.NO_DATA);
        }
        UpdateWrapper<ContactGreet> update = new UpdateWrapper<>();
        String users = greetVo.getUsers().stream().map(ContactVo::getId).collect(Collectors.joining(StrUtils.COMMA));
        if (!contactGreet.getUsers().equals(users)) {
//            Map<String, String> userMap = greetVo.getUsers().stream()
//                    .collect(Collectors.toMap(ContactVo::getId, ContactVo::getName));
//            String error = ContactWayApi.allowExternalOfUsers(userMap, meta);
//            if (StrUtils.isNotEmpty(error)) {
//                return AjaxResult.error(error);
//            }
            update.set("users", users);
        }
        WelcomeVo welcome = greetVo.getWelcome();
        QyWelcomeTemplate template = new QyWelcomeTemplate();
        template.setId(contactGreet.getWelcomeId());
        template.setText(welcome.getText());
        template.setOthers(JSONUtil.toJsonStr(welcome.getOthers()));
        welcomeService.update(template);
        update.set("title", greetVo.getTitle());
        update.eq("id", greetVo.getId());
        greetMapper.update(null, update);
        return AjaxResult.success();
    }

    @Transactional
    @Override
    public AjaxResult deleteGreet(Long greetId, Long teamId) {
        ContactGreet contactGreet = greetMapper.selectById(greetId);
        if (contactGreet.getTeamId().equals(teamId)) {
            welcomeService.deleteById(contactGreet.getWelcomeId());
            greetMapper.deleteById(greetId);
            return AjaxResult.success();
        }
        return AjaxResult.noPermission();
    }

    @Override
    public AjaxResult findGreet(Long id, Long teamId) {
        List<ContactGreetWelcome> greetWelcomes = greetMapper.contactGreetList(id, teamId);
        List<ContactGreetVo> contactGreetVos = contactGreetWelcomeToVO(greetWelcomes, teamId);
        if (CollectionUtils.isNotEmpty(contactGreetVos)) {
            return AjaxResult.success(contactGreetVos.get(0));
        }
        return AjaxResult.error(ErrorConstants.NO_DATA);
    }

    @Override
    public PageInfo greetList(Long greetId, Long teamId) {
        List<ContactGreetWelcome> contactGreetWelcomes = greetMapper.contactGreetList(greetId, teamId);
        PageInfo page = new PageInfo(contactGreetWelcomes);
        page.setList(contactGreetWelcomeToVO(contactGreetWelcomes, teamId));
        return page;
    }

    /**
     * 全局欢迎语转换成vo
     */
    private List<ContactGreetVo> contactGreetWelcomeToVO(List<ContactGreetWelcome> greetWelcomes, Long teamId) {
        if (CollectionUtils.isEmpty(greetWelcomes)) {
            return Collections.emptyList();
        }
        Set<String> userIds = new HashSet<>();
        greetWelcomes.forEach(g -> userIds.addAll(CollectionUtils.toStrList(g.getUsers())));
        Map<String, String> namesMap = contactService.contactNamesMap(userIds, teamId);

        return greetWelcomes.stream()
                .map(w -> {
                    ContactGreetVo vo = new ContactGreetVo();
                    vo.setId(w.getId());
                    vo.setTitle(w.getTitle());
                    vo.setCreatorName(w.getCreator());
                    vo.setModifyTime(w.getModifyTime());
                    vo.setWelcome(w.getWelcome());
                    vo.setUsers(CollectionUtils.toStrList(w.getUsers())
                            .stream()
                            .map(userId -> {
                                ContactVo contact = new ContactVo();
                                contact.setId(userId);
                                contact.setName(namesMap.getOrDefault(userId, "未知"));
                                return contact;
                            }).collect(Collectors.toList()));
                    return vo;
                }).collect(Collectors.toList());
    }
}
